<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "statistics".
 *
 * @property string $id
 * @property string $uid
 * @property string $origin
 * @property string $url
 * @property string $ctime
 * @property string $ltime
 * @property string $utime
 * @property string $tid
 */
class Statistics extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'statistics';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['uid', 'ctime', 'ltime', 'utime', 'tid'], 'integer'],
            [['origin', 'url'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'uid' => '用户id,0未登录',
            'origin' => '来源',
            'url' => '访问地址',
            'ctime' => '访问时间',
            'ltime' => '停留时长',
            'utime' => '最后一次更新时间',
            'tid' => '本表id，用于记录uv',
        ];
    }

    /**
     * 写入访问统计
     */
    public static function log($url, $id = 0)
    {
        $time = time();
        if ($id) {//更新时长
            $sql = 'update statistics set ltime=ltime+' . $time . '-utime,utime=' . $time . ' where id=' . $id;
            Yii::$app->db->createCommand($sql)->execute();
            echo $id;
        } else {//新记录
            $cookiesRequest = Yii::$app->request->cookies;
            $uid = $cookiesRequest->getValue('_login_member_id', 0);

            $session = Yii::$app->session;
            $tid = $session->get('_statistics_id', 0);

            $model = new Statistics();
            $model->uid = $uid;
            $model->ctime = $time;
            $model->utime = $time;
            $model->ltime = 1;//默认时长1秒
            $model->url = $url;
            $model->tid = $tid;
            if ($model->save()) {
                if (!$tid) {
                    $model->tid = $model->id;
                    $model->update();
                    $session->set('_statistics_id', $model->id);
                }
            }
            echo $model->id;
        }
    }
}
